<?php

use support\Db;
use support\Log;


/**
 * Here is your custom functions.
 */

function collect_sql($callable){
    DB::enableQueryLog();
    $return = $callable();
    $sqls = DB::getQueryLog();
    $list = [];
    foreach ($sqls as $sql) {
        if(in_array($sql,['select 1'])) continue;
        $query = $sql['query'];
        $bindings = $sql['bindings'];
        $time = $sql['time'];
        foreach ($bindings as $bind){
            $query = preg_replace('/\?/', (is_numeric($bind) ? $bind : '\'' . $bind . '\''), $query, 1); // 将SQL中的?替换为实际的值
        }
        $slow = $time> 1000 ? 'slow_query' : '';
        $info = "query:{$query} -- time:{$slow} {$time}ms";
        Log::channel('sql_log')->info($info);
        //$list[] = $info;


    }
    DB::flushQueryLog();
    return $return;
}

function object2array($object) {
    $object1 = json_decode( json_encode( $object),true);
    return $object1;
}

function curl($url, $params = '', $return = 1, $header = array(), $cookie = array(), $option = array(), $error_exit = true,$time_out=120)
{
    $ch = curl_init($url); // 初始化curl并设置链接
    // curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 50);
    curl_setopt($ch, CURLOPT_TIMEOUT, $time_out);
    // 设置是否为post传递
    curl_setopt($ch, CURLOPT_POST, (bool)$params);
    // 对于https 设定为不验证证书和host
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, $return);//设置是否返回信息

    if ($cookie) {
        $key = array_keys($cookie);
        curl_setopt($ch, $key[0] == 'jar' ? CURLOPT_COOKIEJAR : CURLOPT_COOKIEFILE, $cookie['file']);
    }

    if ($params) {
        if (is_array($params)) {
            $params = http_build_query($params);
        }
        //print_r($params);
        // POST 数据
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    }

    if ($header) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //设置头信息的地方
    } else {
        PHP_SAPI != 'cli' && curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    }

    foreach ($option as $key => $val) {
        curl_setopt($ch, $key, $val);
    }

    $response = curl_exec($ch); // 执行并接收返回信息

    if (curl_errno($ch) && $error_exit) {
        // 出错则显示错误信息
        exit(curl_error($ch));
    }
    //$info = curl_getinfo($ch);
    //\Illuminate\Support\Facades\Log::info(var_export($info,true));
    if (!empty($option[CURLOPT_HEADER])) {
        // 获得响应结果里的：头大小
        $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        // 根据头大小去获取头信息内容
        $_EVN['CURL_HEADER'] = substr($response, 0, $header_size);
        $response = substr($response, $header_size);
    }
    curl_close($ch); // 关闭curl链接
    return $response;
}

function ipHandle($remote_ip){
    return trim(explode(',',$remote_ip)[0] ?? $remote_ip);
}
function getServerIndex(){
    $hostname = '0'.rand(1,9);
    if(function_exists('exec')){
        exec('hostname',$return);
        $hostname = substr(current($return),-2);
    }
    return $hostname;
}
function requestId($prefix=''){
    $hostname = getServerIndex();
    $return = str_replace('.','s'.$hostname,uniqid($prefix,true));
    return strtoupper($return);
}

function checkUrlInfo($url,$time=1)
{
    $format = null;
    $hdrs = null;
    $https = false;
    if (strpos($url, 'https') === 0) {
        $format = 1;
        $https = true;
        $hdrs = @get_headers($url);
        if($hdrs===false){
            stream_context_set_default( [
                'ssl' => [
                    'verify_host' => false,
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                ],
            ]);
        }
    }
    !$hdrs && $hdrs = @get_headers($url,$format);
    if($hdrs===false && $https && $time<2){
        $time++;
        $url = 'http'.substr($url, strpos($url, 'https') + 5);
        checkUrlInfo($url,$time);
    }
    $status = is_array($hdrs) ? preg_match('/^HTTP\\/\\d+\\.\\d+\\s+2\\d\\d\\s+.*$/', $hdrs[0]) : false;
    if ($status) {
        foreach ($hdrs as $key=> $item) {
            if(is_numeric($key)){
                $column = $item;
            }else{
                $column = $key;
            }
            if (strpos($column, 'Content-Length') === false) continue;

            if(is_numeric($key)){
                $size = str_replace('Content-Length:', '', $item) ?: '';
            }else{
                $size = $item;
            }
            $size = trim($size);
            continue;
        }
    }
    $extension = substr($url, strrpos($url, '.') + 1);
    return [$status, $size ?? 0, $extension];
}

function getEventId($package_id,$unique_idd=''){
    list($t1, $t2) = explode(' ', microtime());
    $time = str_replace('.','',strval((float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000)));
    return $package_id.'_'.$unique_idd .'_'.$time.'_'.getServerIndex().'_'.rand(1000,9999);
}

function getIps($ips,$is_all=false){
    $return = [];
    foreach ($ips as $ip){
        if(filter_var($ip,FILTER_VALIDATE_IP,FILTER_FLAG_NO_PRIV_RANGE|FILTER_FLAG_NO_RES_RANGE)){
            if(!$is_all){
                return $ip;
            }else{
                $return[] = $ip;
            }

        }
    }
    return $is_all ? $return : ($ip ?? '');

}





